1 /*global CompletenessTest, sinon */
3 ( function ( $, mw
, QUnit
) {
6 var mwTestIgnore
, mwTester
, addons
;
9 * Add bogus to url to prevent IE crazy caching
11 * @param {string} value a relative path (eg. 'data/foo.js'
12 * or 'data/test.php?foo=bar').
13 * @return {string} Such as 'data/foo.js?131031765087663960'
15 QUnit
.fixurl = function ( value
) {
16 return value
+ ( /\?/.test( value
) ? '&' : '?' )
17 + String( new Date().getTime() )
18 + String( parseInt( Math
.random() * 100000, 10 ) );
25 // For each test() that is asynchronous, allow this time to pass before
26 // killing the test and assuming timeout failure.
27 QUnit
.config
.testTimeout
= 60 * 1000;
29 // Add a checkbox to QUnit header to toggle MediaWiki ResourceLoader debug mode.
30 QUnit
.config
.urlConfig
.push( {
32 label
: 'Enable ResourceLoaderDebug',
33 tooltip
: 'Enable debug mode in ResourceLoader',
40 * Adds toggle checkbox to header
42 QUnit
.config
.urlConfig
.push( {
43 id
: 'completenesstest',
44 label
: 'Run CompletenessTest',
45 tooltip
: 'Run the completeness test'
51 * Glue code for nicer integration with QUnit setup/teardown
52 * Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
54 * - Work properly with asynchronous QUnit by using module setup/teardown
55 * instead of synchronously wrapping QUnit.test.
57 sinon
.assert
.fail = function ( msg
) {
58 QUnit
.assert
.ok( false, msg
);
60 sinon
.assert
.pass = function ( msg
) {
61 QUnit
.assert
.ok( true, msg
);
66 properties
: [ 'spy', 'stub', 'mock', 'sandbox' ],
67 // Don't fake timers by default
72 var orgModule
= QUnit
.module
;
74 QUnit
.module = function ( name
, localEnv
) {
75 localEnv
= localEnv
|| {};
78 var config
= sinon
.getConfig( sinon
.config
);
79 config
.injectInto
= this;
80 sinon
.sandbox
.create( config
);
82 if ( localEnv
.setup
) {
83 localEnv
.setup
.call( this );
86 teardown: function () {
87 if ( localEnv
.teardown
) {
88 localEnv
.teardown
.call( this );
91 this.sandbox
.verifyAndRestore();
97 // Extend QUnit.module to provide a fixture element.
99 var orgModule
= QUnit
.module
;
101 QUnit
.module = function ( name
, localEnv
) {
103 localEnv
= localEnv
|| {};
106 fixture
= document
.createElement( 'div' );
107 fixture
.id
= 'qunit-fixture';
108 document
.body
.appendChild( fixture
);
110 if ( localEnv
.setup
) {
111 localEnv
.setup
.call( this );
114 teardown: function () {
115 if ( localEnv
.teardown
) {
116 localEnv
.teardown
.call( this );
119 fixture
.parentNode
.removeChild( fixture
);
125 // Initiate when enabled
126 if ( QUnit
.urlParams
.completenesstest
) {
128 // Return true to ignore
129 mwTestIgnore = function ( val
, tester
) {
131 // Don't record methods of the properties of constructors,
132 // to avoid getting into a loop (prototype.constructor.prototype..).
133 // Since we're therefor skipping any injection for
134 // "new mw.Foo()", manually set it to true here.
135 if ( val
instanceof mw
.Map
) {
136 tester
.methodCallTracker
.Map
= true;
139 if ( val
instanceof mw
.Title
) {
140 tester
.methodCallTracker
.Title
= true;
144 // Don't record methods of the properties of a jQuery object
145 if ( val
instanceof $ ) {
149 // Don't iterate over the module registry (the 'script' references would
150 // be listed as untested methods otherwise)
151 if ( val
=== mw
.loader
.moduleRegistry
) {
158 mwTester
= new CompletenessTest( mw
, mwTestIgnore
);
162 * Reset mw.config and others to a fresh copy of the live config for each test(),
163 * and restore it back to the live one afterwards.
165 * @param {Object} [localEnv]
166 * @example (see test suite at the bottom of this file)
169 QUnit
.newMwEnvironment
= ( function () {
170 var warn
, error
, liveConfig
, liveMessages
,
173 liveConfig
= mw
.config
.values
;
174 liveMessages
= mw
.messages
.values
;
176 function suppressWarnings() {
178 error
= mw
.log
.error
;
179 mw
.log
.warn
= mw
.log
.error
= $.noop
;
182 function restoreWarnings() {
183 // Guard against calls not balanced with suppressWarnings()
184 if ( warn
!== undefined ) {
186 mw
.log
.error
= error
;
187 warn
= error
= undefined;
191 function freshConfigCopy( custom
) {
193 // Tests should mock all factors that directly influence the tested code.
194 // For backwards compatibility though we set mw.config to a fresh copy of the live
195 // config. This way any modifications made to mw.config during the test will not
196 // affect other tests, nor the global scope outside the test runner.
197 // This is a shallow copy, since overriding an array or object value via "custom"
198 // should replace it. Setting a config property means you override it, not extend it.
199 // NOTE: It is important that we suppress warnings because extend() will also access
200 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
202 copy
= $.extend( {}, liveConfig
, custom
);
208 function freshMessagesCopy( custom
) {
209 return $.extend( /*deep=*/true, {}, liveMessages
, custom
);
213 * @param {jQuery.Event} event
214 * @param {jqXHR} jqXHR
215 * @param {Object} ajaxOptions
217 function trackAjax( event
, jqXHR
, ajaxOptions
) {
218 ajaxRequests
.push( { xhr
: jqXHR
, options
: ajaxOptions
} );
221 return function ( localEnv
) {
222 localEnv
= $.extend( {
234 // Greetings, mock environment!
235 mw
.config
.values
= freshConfigCopy( localEnv
.config
);
236 mw
.messages
.values
= freshMessagesCopy( localEnv
.messages
);
237 this.suppressWarnings
= suppressWarnings
;
238 this.restoreWarnings
= restoreWarnings
;
240 // Start tracking ajax requests
241 $( document
).on( 'ajaxSend', trackAjax
);
243 localEnv
.setup
.call( this );
246 teardown: function () {
247 var timers
, pending
, $activeLen
;
249 localEnv
.teardown
.call( this );
251 // Stop tracking ajax requests
252 $( document
).off( 'ajaxSend', trackAjax
);
254 // Farewell, mock environment!
255 mw
.config
.values
= liveConfig
;
256 mw
.messages
.values
= liveMessages
;
258 // As a convenience feature, automatically restore warnings if they're
259 // still suppressed by the end of the test.
262 // Tests should use fake timers or wait for animations to complete
263 // Check for incomplete animations/requests/etc and throw if there are any.
264 if ( $.timers
&& $.timers
.length
!== 0 ) {
265 timers
= $.timers
.length
;
266 $.each( $.timers
, function ( i
, timer
) {
267 var node
= timer
.elem
;
268 mw
.log
.warn( 'Unfinished animation #' + i
+ ' in ' + timer
.queue
+ ' queue on ' +
269 mw
.html
.element( node
.nodeName
.toLowerCase(), $( node
).getAttrs() )
272 // Force animations to stop to give the next test a clean start
275 throw new Error( 'Unfinished animations: ' + timers
);
278 // Test should use fake XHR, wait for requests, or call abort()
279 $activeLen
= $.active
;
280 if ( $activeLen
!== undefined && $activeLen
!== 0 ) {
281 pending
= $.grep( ajaxRequests
, function ( ajax
) {
282 return ajax
.xhr
.state() === 'pending';
284 if ( pending
.length
!== $activeLen
) {
285 mw
.log
.warn( 'Pending requests does not match jQuery.active count' );
287 // Force requests to stop to give the next test a clean start
288 $.each( pending
, function ( i
, ajax
) {
289 mw
.log
.warn( 'Pending AJAX request #' + i
, ajax
.options
);
294 throw new Error( 'Pending AJAX requests: ' + pending
.length
+ ' (active: ' + $activeLen
+ ')' );
301 // $.when stops as soon as one fails, which makes sense in most
302 // practical scenarios, but not in a unit test where we really do
303 // need to wait until all of them are finished.
304 QUnit
.whenPromisesComplete = function () {
305 var altPromises
= [];
307 $.each( arguments
, function ( i
, arg
) {
308 var alt
= $.Deferred();
309 altPromises
.push( alt
);
311 // Whether this one fails or not, forwards it to
312 // the 'done' (resolve) callback of the alternative promise.
313 arg
.always( alt
.resolve
);
316 return $.when
.apply( $, altPromises
);
320 * Recursively convert a node to a plain object representing its structure.
321 * Only considers attributes and contents (elements and text nodes).
322 * Attribute values are compared strictly and not normalised.
325 * @return {Object|string} Plain JavaScript value representing the node.
327 function getDomStructure( node
) {
328 var $node
, children
, processedChildren
, i
, len
, el
;
330 if ( node
.nodeType
=== Node
.ELEMENT_NODE
) {
331 children
= $node
.contents();
332 processedChildren
= [];
333 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
335 if ( el
.nodeType
=== Node
.ELEMENT_NODE
|| el
.nodeType
=== Node
.TEXT_NODE
) {
336 processedChildren
.push( getDomStructure( el
) );
341 tagName
: node
.tagName
,
342 attributes
: $node
.getAttrs(),
343 contents
: processedChildren
346 // Should be text node
352 * Gets structure of node for this HTML.
354 * @param {string} html HTML markup for one or more nodes.
356 function getHtmlStructure( html
) {
357 var el
= $( '<div>' ).append( html
)[ 0 ];
358 return getDomStructure( el
);
362 * Add-on assertion helpers
364 // Define the add-ons
367 // Expect boolean true
368 assertTrue: function ( actual
, message
) {
369 QUnit
.push( actual
=== true, actual
, true, message
);
372 // Expect boolean false
373 assertFalse: function ( actual
, message
) {
374 QUnit
.push( actual
=== false, actual
, false, message
);
377 // Expect numerical value less than X
378 lt: function ( actual
, expected
, message
) {
379 QUnit
.push( actual
< expected
, actual
, 'less than ' + expected
, message
);
382 // Expect numerical value less than or equal to X
383 ltOrEq: function ( actual
, expected
, message
) {
384 QUnit
.push( actual
<= expected
, actual
, 'less than or equal to ' + expected
, message
);
387 // Expect numerical value greater than X
388 gt: function ( actual
, expected
, message
) {
389 QUnit
.push( actual
> expected
, actual
, 'greater than ' + expected
, message
);
392 // Expect numerical value greater than or equal to X
393 gtOrEq: function ( actual
, expected
, message
) {
394 QUnit
.push( actual
>= expected
, actual
, 'greater than or equal to ' + expected
, message
);
398 * Asserts that two HTML strings are structurally equivalent.
400 * @param {string} actualHtml Actual HTML markup.
401 * @param {string} expectedHtml Expected HTML markup
402 * @param {string} message Assertion message.
404 htmlEqual: function ( actualHtml
, expectedHtml
, message
) {
405 var actual
= getHtmlStructure( actualHtml
),
406 expected
= getHtmlStructure( expectedHtml
);
420 * Asserts that two HTML strings are not structurally equivalent.
422 * @param {string} actualHtml Actual HTML markup.
423 * @param {string} expectedHtml Expected HTML markup.
424 * @param {string} message Assertion message.
426 notHtmlEqual: function ( actualHtml
, expectedHtml
, message
) {
427 var actual
= getHtmlStructure( actualHtml
),
428 expected
= getHtmlStructure( expectedHtml
);
442 $.extend( QUnit
.assert
, addons
);
445 * Small test suite to confirm proper functionality of the utilities and
446 * initializations defined above in this file.
448 QUnit
.module( 'test.mediawiki.qunit.testrunner', QUnit
.newMwEnvironment( {
450 this.mwHtmlLive
= mw
.html
;
452 escape: function () {
457 teardown: function () {
458 mw
.html
= this.mwHtmlLive
;
468 QUnit
.test( 'Setup', 3, function ( assert
) {
469 assert
.equal( mw
.html
.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
470 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object applied' );
471 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object applied' );
473 mw
.config
.set( 'testVar', 'bar' );
474 mw
.messages
.set( 'testMsg', 'Bar.' );
477 QUnit
.test( 'Teardown', 2, function ( assert
) {
478 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
479 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
482 QUnit
.test( 'Loader status', 2, function ( assert
) {
484 modules
= mw
.loader
.getModuleNames(),
488 for ( i
= 0, len
= modules
.length
; i
< len
; i
++ ) {
489 state
= mw
.loader
.getState( modules
[ i
] );
490 if ( state
=== 'error' ) {
491 error
.push( modules
[ i
] );
492 } else if ( state
=== 'missing' ) {
493 missing
.push( modules
[ i
] );
497 assert
.deepEqual( error
, [], 'Modules in error state' );
498 assert
.deepEqual( missing
, [], 'Modules in missing state' );
501 QUnit
.test( 'htmlEqual', 8, function ( assert
) {
503 '<div><p class="some classes" data-length="10">Child paragraph with <a href="http://example.com">A link</a></p>Regular text<span>A span</span></div>',
504 '<div><p data-length=\'10\' class=\'some classes\'>Child paragraph with <a href=\'http://example.com\' >A link</a></p>Regular text<span>A span</span></div>',
505 'Attribute order, spacing and quotation marks (equal)'
509 '<div><p class="some classes" data-length="10">Child paragraph with <a href="http://example.com">A link</a></p>Regular text<span>A span</span></div>',
510 '<div><p data-length=\'10\' class=\'some more classes\'>Child paragraph with <a href=\'http://example.com\' >A link</a></p>Regular text<span>A span</span></div>',
511 'Attribute order, spacing and quotation marks (not equal)'
515 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
516 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
517 'Multiple root nodes (equal)'
521 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
522 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
523 'Multiple root nodes (not equal, last label node is different)'
527 'fo"o<br/>b>ar',
529 'Extra escaping is equal'
534 'Text escaping (not equal)'
538 'foo<a href="http://example.com">example</a>bar',
539 'foo<a href="http://example.com">example</a>bar',
540 'Outer text nodes are compared (equal)'
544 'foo<a href="http://example.com">example</a>bar',
545 'foo<a href="http://example.com">example</a>quux',
546 'Outer text nodes are compared (last text node different)'
551 QUnit
.module( 'test.mediawiki.qunit.testrunner-after', QUnit
.newMwEnvironment() );
553 QUnit
.test( 'Teardown', 3, function ( assert
) {
554 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() callback was ran.' );
555 assert
.equal( mw
.config
.get( 'testVar' ), null, 'config object restored to live in next module()' );
556 assert
.equal( mw
.messages
.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
559 }( jQuery
, mediaWiki
, QUnit
) );